package com.pb.infra.dynamicSetting.dynamTableCfg.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pb.infra.auth.entity.pbsys.PriviMenu;
import com.pb.infra.auth.entity.pbsys.PriviMenuExample;
import com.pb.infra.auth.mapper.custom.PriviMenuCustomMapper;
import com.pb.infra.auth.mapper.pbsys.PriviMenuMapper;
import com.pb.infra.dynamicSetting.dynamTableCfg.dto.TableCfgReleaseMenuDTO;
import com.pb.infra.dynamicSetting.dynamTableCfg.entity.MaFrDynamTableCfg;
import com.pb.infra.dynamicSetting.dynamTableCfg.mapper.MaFrDynamTableCfgMapper;
import com.pb.infra.dynamicSetting.dynamTableColumnCfg.mapper.MaFrDynamTableColumnCfgMapper;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.oth.util.DateTimeUtil;
import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.infra.oth.util.UserInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 动态表管理(MaFrDynamTableCfg)表服务实现类
 *
 * @author makejava
 * @since 2022-03-09 14:57:33
 */
@Service("MaFrDynamTableCfgService")
public class MaFrDynamTableCfgService {

    @Resource
    private JwtTokenConfig jwtTokenConfig;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Resource
    private PriviMenuMapper priviMenuMapper;

    @Resource
    private PriviMenuCustomMapper priviMenuCustomMapper;

    @Resource
    private MaFrDynamTableCfgMapper maFrDynamTableCfgMapper;

    @Resource
    private MaFrDynamTableColumnCfgMapper maFrDynamTableColumnCfgMapper;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public Result queryById(String id) {
        return Result.ok(this.maFrDynamTableCfgMapper.queryById(id));
    }

    /**
     * 分页查询
     *
     * @param maFrDynamTableCfg 筛选条件
     * @return 查询结果
     */
    public Result selectAll(MaFrDynamTableCfg maFrDynamTableCfg) {

        if (maFrDynamTableCfg.getPageIndex() != null && maFrDynamTableCfg.getPageSize() != null) {
            PageHelper.startPage(maFrDynamTableCfg.getPageIndex(), maFrDynamTableCfg.getPageSize());
        }

        List<MaFrDynamTableCfg> list = this.maFrDynamTableCfgMapper.queryList(maFrDynamTableCfg);

//        MaFrDynamTableColumnCfg columnCfg=new MaFrDynamTableColumnCfg();
//        list.forEach(item -> {
//            columnCfg.setTableId(item.getId());
//
//            item.setColumn(maFrDynamTableColumnCfgMapper.queryList(columnCfg));
//            item.getColumn().forEach(cItem -> {
//                if (cItem.getPropsJson() != null) {
//                    DictVO dVO = JSON.parseObject(cItem.getPropsJson(), DictVO.class);
//                    cItem.setDictLabel(dVO.getLabel());
//                    cItem.setValue(dVO.getValue());
//                    cItem.setProps(dVO);
//                }
//            });
//
//        });
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    /**
     * 新增数据
     *
     * @param maFrDynamTableCfg 实例对象
     * @return 实例对象
     */
    @Transactional
    public Result insert(MaFrDynamTableCfg maFrDynamTableCfg) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        maFrDynamTableCfg.setDataDt(sdf1.format(new Date()));

        String maxId = maFrDynamTableCfgMapper.maxId(new MaFrDynamTableCfg());
        if (maxId == null) {
            //默认格式
            maxId = "TyyyyMM0000";
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

        String tableId = "T" + sdf.format(new Date()) + String.format("%04d", Integer.parseInt(maxId.substring(7, maxId.length())) + 1);


        maFrDynamTableCfg.setId(tableId);


//        int i = 0;
//        for (MaFrDynamTableColumnCfg item : maFrDynamTableCfg.getColumn()
//        ) {
//            item.setTableId(tableId);
//
//            item.setId("" + i);
//
//            DictVO dVO = new DictVO();
//            dVO.setLabel(item.getDictLabel());
//            dVO.setValue(item.getValue());
//            item.setProps(dVO);
//            item.setPropsJson(JSON.toJSONString(item.getProps()));
//            item.setSearch(item.getSearch() == null ? false : item.getSearch());
//            item.setIsLike(item.getIsLike() == null ? false : item.getIsLike());
//            maFrDynamTableColumnCfgMapper.insert(item);
//            i = i + 1;
//        }

        return Result.ok(this.maFrDynamTableCfgMapper.insert(maFrDynamTableCfg));
    }

    /**
     * 修改数据
     *
     * @param maFrDynamTableCfg 实例对象
     * @return 实例对象
     */
    public Result update(MaFrDynamTableCfg maFrDynamTableCfg) {
//        maFrDynamTableColumnCfgMapper.delTableCol(maFrDynamTableCfg.getId());
//        int i = 0;
//        for (MaFrDynamTableColumnCfg item : maFrDynamTableCfg.getColumn()
//        ) {
//            item.setTableId(maFrDynamTableCfg.getId());
//            item.setId("" + i);
//
//            DictVO dVO = new DictVO();
//            dVO.setLabel(item.getDictLabel());
//            dVO.setValue(item.getValue());
//            item.setProps(dVO);
//            item.setPropsJson(JSON.toJSONString(item.getProps()));
//            item.setSearch(item.getSearch());
//            item.setIsLike(item.getIsLike());
//            maFrDynamTableColumnCfgMapper.insert(item);
//            i = i + 1;
//        }

        return Result.ok(this.maFrDynamTableCfgMapper.update(maFrDynamTableCfg));
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Transactional
    public Result deleteById(String id) {

        PriviMenuExample example =new PriviMenuExample();
        PriviMenuExample.Criteria criteria = example.createCriteria();
        criteria.andEnNameEqualTo("dynamicTable"+id);
        //删除相关的菜单
        priviMenuMapper.deleteByExample(example);

        maFrDynamTableColumnCfgMapper.delTableCol(id);
        return Result.ok(this.maFrDynamTableCfgMapper.deleteById(id) > 0);
    }

    @Transactional
    public Result releaseMenu(TableCfgReleaseMenuDTO dto, HttpServletRequest request) {
        PriviMenu menu = new PriviMenu();
        String enName = "dynamicTable" + dto.getTableParam().getId();
        String token = request.getHeader(jwtTokenConfig.getHeader());
        //通过token在redis中获取用户信息
        UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
        PriviMenu oldMenu = priviMenuCustomMapper.selectEnName(enName);
        //不等于空修改菜单名称反之添加
        if (oldMenu != null) {
            menu.setMenuId(oldMenu.getMenuId());
            menu.setCnName(dto.getTableParam().getDynamTableNickName());
            priviMenuMapper.updateByPrimaryKeySelective(menu);
        } else {
            menu.setMenuId(String.valueOf(priviMenuCustomMapper.getMaxMenuId()));
            menu.setEnName("dynamicTable" + dto.getTableParam().getId());
            //表格名称配置为菜单名称
            menu.setCnName(dto.getTableParam().getDynamTableNickName());
            dto.setMenuId(dto.getUpperId());
            menu.setUpperId(dto.getUpperId());
            menu.setLevelId(new BigDecimal(dto.getLevelId()));
            menu.setSerialNo(new BigDecimal(priviMenuCustomMapper.getMaxSeqId()));
            menu.setMenuPath("dynamicTableView?tableId=" + dto.getTableParam().getId());
            menu.setMenuIcon("el-icon-receiving");
            menu.setCatalogFlag("1");
            menu.setComponent("dynamicSettingTable/dynamicTableView");
            menu.setFromType("0");
            menu.setHideFlag("1");
            menu.setSysFlag("0");
            menu.setCreateUser(userInfo.getUserId());
            menu.setUpdateUser(userInfo.getUserId());
            menu.setCreateTime(DateTimeUtil.getStrFromNewDate());
            menu.setUpdateTime(DateTimeUtil.getStrFromNewDate());
            menu.setAppId(dto.getAppId());
            priviMenuMapper.insert(menu);
        }
        return Result.ok("发布完成");
    }
}
